<template>
  <div class="room-action">
    <van-field
      type="text"
      class="input"
      :border="false"
      placeholder="问医生"
      autocomplete="off"
      v-model.trim="msg"
      @keyup.enter="sendText"
      :disabled="status !== OrderType.ConsultChat"
    ></van-field>
    <van-uploader
      :preview-image="false"
      :disabled="status !== OrderType.ConsultChat"
      :after-read="onAfertRead"
    >
      <cp-icon name="consult-img" />
    </van-uploader>
  </div>
</template>

<script setup lang="ts">
import { uploadFile } from '@/api/consult'
import { OrderType } from '@/enums'
import type { Image } from '@/types/consult'
import { showLoadingToast } from 'vant'
import type { UploaderAfterRead } from 'vant/lib/uploader/types'
import { ref } from 'vue'

defineProps<{
  status?: OrderType
}>()

const emit = defineEmits<{
  (e: 'send-text', msg: string): void
  (e: 'send-image', msg: Image): void
}>()

const msg = ref('')
const sendText = () => {
  emit('send-text', msg.value)
  msg.value = '' // 清空输入框
}

// 上传图片
const onAfertRead: UploaderAfterRead = async (items) => {
  if (Array.isArray(items)) return
  if (!items.file) return

  // 1. 页面整体出现一个loading,告诉用户当前正在处理图片上传...
  const toast = showLoadingToast({
    message: '上传中，请稍后...',
    duration: 0
  })

  // 2. 图片上传服务器 得到图片的公网url地址
  const formData = new FormData()
  formData.append('file', items.file)
  const res = await uploadFile(formData)
  console.log(res)

  toast.close()

  // 3. 通过子传父 把图片给父组件  父组件接力调用socket发消息给后台
  emit('send-image', res.data)
}
</script>

<style lang="scss" scoped>
.room-action {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 60px;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 0 16px;
  z-index: 1;
  box-sizing: border-box;
  .input {
    background-color: var(--cp-bg);
    border: none;
    border-radius: 25px;
    margin-right: 10px;
    padding: 8px 15px;
  }
  .cp-icon {
    width: 24px;
    height: 24px;
  }
}
</style>
